import React from 'react';
import { WeaErrorPage, WeaTools, WeaTextarea } from 'ecCom';
import Immutable from 'immutable';
const { is, fromJS } = Immutable; 
//便签元素
class ScratchpadCom extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            text: props.data.text,
            disabled: false,
        }
        this.getBytesLength = this.getBytesLength.bind(this);
        this.subStringByBytes = this.subStringByBytes.bind(this);
        this.saveScratchpad = this.saveScratchpad.bind(this);
        this.saveContent = this.saveContent.bind(this);
    }
    getBytesLength(str) {
	    // 在GBK编码里，除了ASCII字符，其它都占两个字符宽
	    return str.replace(/[^\x00-\xff]/g, 'xx').length;
	}
	subStringByBytes(val, maxBytesLen) {
	    var len = maxBytesLen;
	    var result = val.slice(0, len);
	    while (getBytesLength(result) > maxBytesLen) {
	        result = result.slice(0, --len);
	    }
	    return result;
	}
	saveScratchpad(padcontent){
		this.state = {
            text: padcontent,
            disabled: true,
        }
        const len = this.getBytesLength(padcontent);
        if (len > 4000) {
            const reply = confirm("便签内容超过4000字节,内容将被截取,是否保存?");
            if (reply) {
                padcontent = subStringByBytes(padcontent, 4000);
                this.saveContent(padcontent);
            } else {
                this.state = {
		            disabled: false,
		        }
            }
        } else {
            this.saveContent(padcontent);
        }
	}
	saveContent(padcontent){
		const { eid, data } = this.props;
		const { userid } = data;
	    WeaTools.callApi('/api/portal/scratchpad/saveScratchpad', 'POST', {
            eid,
            userid,
            operation: 'save',
            padcontent
        },'text').then((result)=>{
	        this.state = {
	            disabled: false,
	        }
	    })
	}
	shouldComponentUpdate(nextProps){
		return !is(fromJS(this.props),fromJS(nextProps))
	}
	render() {
		const { eid, data } = this.props;
		const { text, disabled } = this.state;
		return <div id={`scratchpad_${eid}`}>
	           	 <WeaTextarea 
	           	 	id={`scratchpadarea_${eid}`}
	           	 	minRows={parseInt(data.height)/20}
	           	 	style={{height:data.height}}
	           	 	value={text} viewAttr={disabled ? 1 : 2} 
	           	 	onBlur={this.saveScratchpad}/>
			  </div>
	}
}

class MyErrorHandler extends React.Component {
	render() {
		const hasErrorMsg = this.props.error && this.props.error !== "";
		return (
			<WeaErrorPage msg={hasErrorMsg?this.props.error:"对不起，该页面异常，请联系管理员！"} />
		);
	}
}
ScratchpadCom = WeaTools.tryCatch(React, MyErrorHandler, { error: "" })(ScratchpadCom);
export default ScratchpadCom;